/**
 * 登录日志
 */
var loginLogUI = function() {
    var self = this;
    PageList.call(self);

    self.table = null;
    self.startInput = null;
    self.endInput = null;
    self.userInput = null;
};
loginLogUI.prototype = Object.create(PageList.prototype);

loginLogUI.prototype.init = function() {
    var self = this;
    
    self.jumpPage = function(page) {
        self.refresh(page);
    };
    self.refresh(1);
}

loginLogUI.prototype.refresh = function(page) {
    var self = this;
    var start = null, end = null, uid = null, ip = null;
    if (self.startInput && self.startInput.val()) {
        start = self.startInput.val();
        start = new Date(start).Format("yyyy-MM-dd");
    }
    if (self.endInput && self.endInput.val()) {
        end = self.endInput.val();
        end = new Date(end).Format("yyyy-MM-dd");
    }
    if (self.userInput && self.userInput.val().trim()) {
        uid = self.userInput.val().trim();
    }
    if (self.ipInput && self.ipInput.val().trim()) {
        ip = self.ipInput.val().trim();
    }

    var data = {
        pageNum: page || 1,
        pageSize: self.getPageSize(),
    }
    if (uid) data.uid = uid;
    if (ip) data.ip = ip;
    if (start) data.start = start;
    if (end) data.end = end;
    CMD.user_log_query(data, function(r) {
        self.fillResults(r);
    });
}

loginLogUI.prototype.fillResults = function(list) {
    var self = this;
    self.list = list.list;
    self.table.empty();
    self.fillPages(list.count, list.number, list.page, list.size);

    var ips = [];
    for (var i in self.list) {
        var d = self.list[i];
        var tr = $("<tr></tr>");
        if (d.in)
            tr.append('<td>' + new Date(d.in).Format("yyyy-MM-dd HH:mm:ss") + '</td>');
        else
            tr.append('<td> </td>');
        if (d.out)
            tr.append('<td>' + new Date(d.out).Format("yyyy-MM-dd HH:mm:ss") + '</td>');
        else
            tr.append('<td> </td>');
        tr.append("<td>" + (d.user.mobile || '') + '</td>');
        tr.append("<td class='ip'>" + (d.ip || '') + '</td>');
        tr.append("<td>" + (d.source || '') + '</td>');
        tr.append("<td>" + (d.url || '') + '</td>');
        self.table.append(tr);
        if (d.ip && ips.indexOf(d.ip) == -1) ips.push(d.ip);
    }

    var arr = $("td.uri");
    for (var i = 0; i < arr.length; i++) {
        self.registerPopover($(arr[i]), i);
    }

    for (var i in ips) self.registerIp(ips[i]);
}

loginLogUI.prototype.registerIp = function(ip) {
    CMD.ip_info(ip, function(r) {
        var arr = $("td.ip");
        for (var i = 0; i < arr.length; i++) {
            if ($(arr[i]).html() == ip) {
                $(arr[i]).html(ip + "(" + r.addr + ")");
            }
        }
    });
}

window.LoginLogUI = new loginLogUI();
